package ru.spb.osll.myfit.server.handler;

import org.apache.log4j.Logger;
import ru.spb.osll.myfit.common.Page;
import ru.spb.osll.myfit.common.PageElement;
import ru.spb.osll.myfit.common.Table;
import ru.spb.osll.myfit.common.TableStyle;
import ru.spb.osll.myfit.server.Converter;
import ru.spb.osll.myfit.server.parser.PageParser;
import ru.spb.osll.myfit.server.parser.TableUtils;
import ru.spb.osll.myfit.util.IOUtils;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

public class PageLoader {
  private static Logger LOG = Logger.getLogger(PageLoader.class);
  private TableUtils m_tableUtils;
  private PageParser m_parser;// = new PageParser(new Converter());

  public PageLoader() {
    m_parser = new PageParser(new Converter());
  }

  public PageLoader(TableUtils tableUtils) {
   this();
    m_tableUtils = tableUtils;
  }

  public Page loadPage(String fileName) throws IOException{
    Page page = new Page();
    List<String> lines = readPageFile(fileName);
    List<PageElement> pageElements = m_parser
          .parsePage(new ArrayList<String>(lines));

    for (PageElement element : pageElements) {
      if(element instanceof Table){
        setTableStyle((Table)element);
      }
      page.insert(element);
    }

    return page;
  }



  private void setTableStyle(Table table) {
    if (m_tableUtils != null) {
      TableStyle style = m_tableUtils.getTableStyle(table);
      table.setStyle(style);
    }
  }

  public List<String> readPageFile(final String fileName) throws IOException,
      FileNotFoundException {
    LOG.info("Loading page, path: " + fileName);
    return IOUtils.readFile(fileName);
  }
}
